package com.trans.utils;

import com.trans.entity.RequestInfo;
import com.trans.interf.ResultHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpRequestInterceptor;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author xwduo
 * @Date 2024-01-19 15:05
 */
@Slf4j
public class HttpRemoteUtils {

    public static List<Map<String,Object>> request(RequestInfo requestInfo, List<String> keys){
        if( null != keys && !keys.isEmpty() ){
            StringBuilder urlBuilder = new StringBuilder(requestInfo.url);
            if(!requestInfo.url.endsWith("/")){
                urlBuilder.deleteCharAt(urlBuilder.length());
            }
            HttpUriRequestBase requestBase = null;
            switch (requestInfo.methodName){
                case HttpGet.METHOD_NAME:
                    urlBuilder.append("?").append(requestInfo.paramsName).append("=").append(String.join(",", keys));
                    requestBase =  new HttpGet(urlBuilder.toString());
                    break;
                case HttpPost.METHOD_NAME:
                    requestBase = new HttpPost(urlBuilder.toString());

                    break;
                default:return Collections.emptyList();
            }
            return doRequest(requestBase, requestInfo.resultHandle,requestInfo.interceptorList);
        }
        return Collections.emptyList();
    }

    private static  List<Map<String,Object>> doRequest(HttpUriRequestBase requestBase , Class<? extends ResultHandle> clazz,List<HttpRequestInterceptor> interceptorList ){
        String resultContent = null;
        HttpClientBuilder custom = HttpClients.custom();
        if( ! interceptorList.isEmpty()){
            interceptorList.forEach(custom::addRequestInterceptorLast);
        }
        try(CloseableHttpClient httpClient = custom.build()) {
            String execute = httpClient.execute(requestBase, new BasicHttpClientResponseHandler());
            ResultHandle handle = clazz.newInstance();
            return handle.handleResult(execute);
        }catch (Exception e){
            log.error("远程请求失败：{}",e.getMessage());
            return null;
        }
    }


}
